package com.qingfeng.core.dao.qingfeng;

import com.github.pagehelper.PageInfo;
import com.qingfeng.core.aop.exception.HttpException;
import com.qingfeng.core.config.database.BaseMapper;
import com.qingfeng.core.dao.BaseDao;
import com.qingfeng.core.entity.qingfeng.Coupons;
import com.qingfeng.core.mapper.qingfeng.CouponsMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @description: 任务
 * @author:LWY
 * @date: 2017/10/16 17:15
 * @modified:
 */

@Repository
public class CouponsDao extends BaseDao<Coupons> {

    @Autowired
    CouponsMapper couponsMapper;

    @Override
    protected BaseMapper<Coupons> getBaseMapper() {
        return couponsMapper;
    }

    /**
     * 获取优惠券
     *
     * @param state 0:全部,1:可用,2:不可用
     * @return
     */
    public PageInfo<Coupons> get(Integer pageNum, Integer pageSize, Integer state, String user_id) {
        Example example = new Example(Coupons.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(user_id)) {
            criteria.andEqualTo("user_id", user_id);
        }
        if (state == 2) {
            //在有效期之内
            criteria.andEqualTo("state", state);
            criteria.andCondition("validity_start<now() and validity_end>now()");
        }
        if (state == 3) {
            //在有效期之外
            criteria.andCondition(" state=3 or state=4 or validity_start>now() or validity_end<now()");
        }
        return super.get(pageNum, pageSize, example);
    }

    /**
     * 使用优惠券
     *
     * @param id 优惠券id
     * @return 优惠券信息
     */
    public Coupons use(String id) {
        Coupons coupons = new Coupons();
        coupons.setId(id);
        coupons.setState(3);
        coupons.setUse_time(new Date());
        couponsMapper.updateByPrimaryKeySelective(coupons);
        return super.byId(id);
    }

    /**
     * 兑换优惠码
     *
     * @param coupons_id 优惠码
     * @param user_id    用户id
     */
    public void exchange(String coupons_id, String user_id) {
        Coupons coupons =byId(coupons_id);
        if (coupons == null) {
            throw new HttpException("不存在的兑换码");
        }
        Integer state = coupons.getState();
        if (state == 4) {
            throw new HttpException("该兑换码已经被禁用，禁用原因:" + coupons.getDisable_rease());
        }
        if (state != 1) {
            throw new HttpException("该兑换码已经被使用");
        }
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis > coupons.getValidity_end().getTime()) {
            throw new HttpException("该兑换码已经过期");
        }
        coupons.setUser_id(user_id);
        coupons.setExchange_time(new Date());
        //2:已兑换未使用
        coupons.setState(2);
        couponsMapper.updateByPrimaryKeySelective(coupons);
    }
}
